// pages/collect/collect.js
Page({
  data: {
    collectGoods: [],
    activeIndex: 0
  },
  onLoad: function() {
    this.loadCollectGoods();
  },
  onShow: function() {
    this.setData({
      collectGoods: []
    });
    this.loadCollectGoods();
  },
  loadCollectGoods: function() {
    const collectList = wx.getStorageSync('collectList') || {};
    for (const goodsId in collectList) {
      if (collectList[goodsId]) {
        this.getGoodsDetail(goodsId);
      }
    }
  },
  getGoodsDetail: function(goodsId) {
    const url = 'https://api-hmugo-web.itheima.net/api/public/v1/goods/detail/?goods_id=' + goodsId;
    wx.request({
      url: url,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.message) {
          const goodsDetail = res.data.message;
          const exists = this.data.collectGoods.some(item => item.goods_id === goodsDetail.goods_id);
          if (!exists) {
            this.setData({
              collectGoods: [...this.data.collectGoods, goodsDetail]
            });
          }
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    });
  },
  onTitleBtnTap: function(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      activeIndex: index
    });
  },
  onGoodsDetail: function(event) {
    const gid = event.currentTarget.dataset.gid;
    console.log('onGoodsDetail gid:', gid);  
    wx.navigateTo({
      url: `/pages/goodsdetails/goodsdetails?gid=${gid}`
    });
  }
});

